package com.baijiayun.liveuibase.zxing;

import android.app.Activity;
import android.graphics.Bitmap;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.qrcode.QRCodeWriter;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by pengwenjian on 2020/11/10
 * Describe:
 */
public class ZxingUtils {

    public static void startScan(Activity activity) {
        new IntentIntegrator(activity)
                .setCaptureActivity(ScanActivity.class)
                .setBeepEnabled(false)
                .initiateScan(); // 初始化扫描
    }

    public static Bitmap generateQRCodeBitmap(String content,int width,int height) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, String> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        try {
            BitMatrix encode = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            int[] pixels = new int[width * height];
            for (int i = 0; i < height; i++) {
                for (int j = 0; j < width; j++) {
                    if (encode.get(j, i)) {
                        pixels[i * width + j] = 0x000000;
                    } else {
                        pixels[i * width + j] = 0xffffff;
                    }
                }
            }
            return Bitmap.createBitmap(pixels, 0, width, width, height, Bitmap.Config.RGB_565);
            //根据官方文档显示stride：Number of colors in the array between rows (must be >= width or <= -width).
            // 即Bitmap.createBitmap方法中第三个参数需要大于width。
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }
}
